package com.woniu.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.exception.orderInfo.OrderInfoException;
import com.woniu.product.model.Goods;
import com.woniu.product.dao.GoodsDao;
import com.woniu.product.param.*;
import com.woniu.product.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.util.OSSUtil;
import com.woniu.util.RedisKeyUtil;
import com.woniu.util.RedisUtil;
import io.seata.spring.annotation.GlobalTransactional;
import net.sf.cglib.beans.BulkBean;
import org.springframework.stereotype.Service;
import org.springframework.ui.context.Theme;

import javax.annotation.Resource;
import javax.lang.model.util.ElementScanner6;
import java.awt.print.PrinterAbortException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 杜岷芫
 * @since 2024年07月12日
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, Goods> implements GoodsService {
  @Resource
   private GoodsDao goodsDao;
  @Resource
  private RedisUtil redisUtil;


    /**
     * 新增商品
     * @param param
     * @throws Exception
     */
    @Override
    public void insertGoods(AddGoodsParam param) throws Exception {
        //compareTo 方法用来比较BigDecimal类型    返回三个可能的值：-1（小于）、0（等于）、1（大于）
        if (param.getGoodsPrice().compareTo(BigDecimal.ZERO)<0){
            throw new OrderInfoException(500,"输入价格有误");
        }
        if(param.getGoodsNum()<=0){
            throw new OrderInfoException(500,"输入数量有误");
        }
        Goods goods = BeanUtil.toBean(param, Goods.class);
        goods.setGoodsState(2);//新增商品设置为下架，再点击上架
        goods.setGoodsFrooze(0);//冻结量0
        goodsDao.insert(goods);





    }

    /**
     * 上架商品
     * @param goodsId
     * @throws Exception
     */
    @Override
    public void enable(Integer goodsId) throws Exception {
        Goods goods = goodsDao.selectById(goodsId);
        if (goods==null){
            throw new OrderInfoException(500,"上架商品不存在");
        }
        if (goods.getGoodsState().equals(1)){
            throw new OrderInfoException(500,"商品已经是上架状态");
        }
        goods.setGoodsState(1);
        goodsDao.updateById(goods);
    }

    /**
     * 下架商品
     * @param goodsId
     * @throws Exception
     */
    @Override
    public void disable(Integer goodsId) throws Exception {
        Goods goods = goodsDao.selectById(goodsId);
        if (goods==null){
            throw new OrderInfoException(500,"下架商品不存在");
        }
        if (goods.getGoodsState().equals(2)){
            throw new OrderInfoException(500,"商品已经下架");
        }
        goods.setGoodsState(2);
        goodsDao.updateById(goods);
    }

    /**
     * 添加商品到购物车
     * @param param
     * @throws Exception
     */
    @Override
    public void addShopping(AddShoppingParam param) throws Exception {
        Goods goods = goodsDao.selectById(param.getGoodsId());
        if (goods == null) {
            throw new OrderInfoException(500, "商品不存在");
        }
        if (goods.getGoodsNum()<=0){
            throw new OrderInfoException(500,"数量不足");
        }
        if (goods.getGoodsState().equals(2)){
            throw new OrderInfoException(500,"商品状态有误");
        }

        if (redisUtil.zscore(RedisKeyUtil.userShopping(param.getUserId()), param.getGoodsId() + "") == null) {
            //如果是null说明购物车里面没有这个商品
            redisUtil.zadd(RedisKeyUtil.userShopping(param.getUserId()), param.getGoodsId() + "", System.currentTimeMillis());
            //向redis中新增一个hash数据，保存完整的购物信息
            HashMap<String, Object> map = new HashMap<>();
            map.put("GoodsId", goods.getGoodsId() + "");
            map.put("GoodsName", goods.getGoodsName());
            map.put("GoodsPrice", goods.getGoodsPrice().toString());
            map.put("GoodsImage", goods.getGoodsImage());
            map.put("GoodsNumber", param.getNum() + "");


            redisUtil.hmmset(RedisKeyUtil.shoppingInfo(param.getUserId(), param.getGoodsId()), map);


        }else {

            redisUtil.hincrbyy(RedisKeyUtil.shoppingInfo(param.getUserId(), param.getGoodsId()), param.getNum());
        }
    }

    /**
     * 购物车删除商品
     * @param param
     * @throws Exception
     */
    @Override
    public void delShopping(AddShoppingParam param) throws Exception {
        Goods goods = goodsDao.selectById(param.getGoodsId());
        if (goods==null){
            throw new OrderInfoException(500,"商品不存在");
        }
        if (redisUtil.zscore(RedisKeyUtil.userShopping(param.getUserId()),param.getGoodsId()+"")!=null){
            redisUtil.zsetRemove(RedisKeyUtil.userShopping(param.getUserId()), param.getGoodsId() + "");
            redisUtil.delete(RedisKeyUtil.shoppingInfo(param.getUserId(), param.getGoodsId()));

        }else{
            throw new OrderInfoException(500,"购物车还没有商品");
        }
    }

    /**
     * 购物车商品数量修改
     * @param param
     * @throws Exception
     */

    @Override
    public void updateShopping(UpdateShoppingParam param) throws Exception {
        Goods goods = goodsDao.selectById(param.getGoodsId());
        if (goods==null){
            throw new OrderInfoException(500,"商品不存在");
        }
        if (goods.getGoodsState()!=1){
            throw new OrderInfoException(500,"商品未上架");
        }
        if (goods.getGoodsNum()<=0){
            throw new OrderInfoException(500,"数量异常");
        }
        redisUtil.hsset(RedisKeyUtil.shoppingInfo(param.getUserId(),param.getGoodsId()),"GoodsNum", param.getNum());
    }

    /**
     * 修改商品图片
     * @param param
     * @throws Exception
     */
    @Override
    @GlobalTransactional(rollbackFor = Throwable.class)
    public void updateImage(UpdateImageParam param) throws Exception {

        try {
            Goods goods = goodsDao.selectById(param.getGoodsId());
            if (goods == null) {
                throw new OrderInfoException(500, "该商品不存在");
            }
            if (goods.getGoodsState().equals(2)) {
                throw new OrderInfoException(500, "该商品已下架");
            }
            goods.setGoodsImage(param.getGoodsImage());
            goodsDao.updateById(goods);
        } catch (Exception e) {
            //一旦报错，就把阿里云新上传的文件删除掉
            OSSUtil.deleteFile("zenghongwei", FileUtil.getName(param.getGoodsImage()));
            System.out.println("进入了catch");
            throw e;//让AOP还是能拿到异常，做回滚
        }
    }

    /**
     * 修改商品信息
     * @param param
     * @throws Exception
     */
    @Override
    public void updateGoods(UpdateGoodsParam param) throws Exception {
        Goods goods = goodsDao.selectById(param.getGoodsId());
        if(goods== null){
            throw new OrderInfoException(500,"商品信息不存在");
        }
        if (goods.getGoodsNum()<=0){
            throw new OrderInfoException(500,"商品数量有误");
        }
        if (goods.getGoodsPrice().compareTo(BigDecimal.ZERO)==0){
            throw new OrderInfoException(500,"输入价格有误");
        }
        goods.setGoodsName(param.getGoodsName());
        goods.setGoodsNum(param.getGoodsNum());
        goods.setGoodsPrice(param.getGoodsPrice());
        goodsDao.updateById(goods);
    }

    /**
     * 商品分页查询
     * @param param
     * @return
     * @throws Exception
     */
    @Override
    public Page<Goods> pageGoods(PageGoodsParam param) throws Exception {

        if (param.getPageNum()==null){
            param.setPageNum(1);
        }
        if(param.getPageSize()==null){
            param.setPageSize(5);
        }

        //条件拼接
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        return goodsDao.selectPage(new Page<Goods>(param.getPageNum(), param.getPageSize()), wrapper);

    }
}
